<template>

	<view class="bg-[var(--page-bg-color)] min-h-screen overflow-hidden order-list" :style="themeColor()">
		<view class="fixed left-0 top-0 right-0 z-10 bg-[#fff]" v-if="statusLoading">
			<view class="py-[24rpx] flex items-center justify-between px-[20rpx]">
				<view class="flex-1 bg-[#fafafa] p-[10rpx] rounded-[8rpx] mr-[20rpx]">
					{{ time_type == '0' ? '创建时间' : '交易时间' }}: {{ create_time_str }}
				</view>
				<view class="nc-iconfont nc-icon-shaixuanV6xx !text-[40rpx] leading-[36rpx] text-[var(--text-color-light6)]"
					@click="handleSelectOrderSearch"></view>

			</view>

			<!-- 门店订单/个人订单 -->
			<view v-if="orderShowType == 'employee'" class="bg-[var(--page-bg-color)] p-[20rpx]">
				<u-subsection :list="searchType" @change="updateSearchType" mode="button" activeColor="var(--primary-color)"
					:fontSize="14" :current="searchTypeIndex"></u-subsection>
			</view>
		</view>

		<mescroll-body ref="mescrollRef" :top="orderShowType == 'employee' ? '200rpx' : '118rpx'" @init="mescrollInit"
			:down="{ use: false }" @up="getShopOrderFn">
			<view class="sidebar-margin pt-[var(--top-m)]" v-if="list.length">
				<template v-for="(item, index) in list" :key="index">
					<view class="mb-[var(--top-m)] card-template">
						<view @click.stop="toLink(item)">
							<view class="flex justify-between items-center">

								<view class="text-[#303133] text-[28rpx] font-400 leading-[36rpx] ">
									<text>销售时间:</text>
									<text class="ml-[10rpx]">{{ timeFormat(item?.tradeTime, 'yyyy-mm-dd hh:MM:ss') }}</text>
								</view>
								<view class="text-[var(--primary-color)] text-[28rpx] leading-[34rpx]"
									:class="{ 'text-primary': item.status == 0, '!text-[var(--text-color-light9)]': item.status == 10 || item.status == 40 }">
									{{ formatOrderStatus(item) }}</view>
							</view>
							<u-line dashed margin="10rpx 0"></u-line>
							<view class="flex justify-between items-center">
								<view class="text-[#303133] text-[28rpx] font-400 leading-[36rpx]">
									<text>{{ t('orderNo') }}:</text>
									<text class="ml-[10rpx]">{{ item.no }}</text>
									<text class="text-[#303133] text-[28rpx] font-400 nc-iconfont nc-icon-fuzhiV6xx1 ml-[11rpx]"
										@click.stop="copy(item.no)"></text>
								</view>

								<view class="text-[#303133] text-[28rpx] font-400 leading-[36rpx] ">
									<text class="ml-[10rpx]">{{ formatOrderType(item) }}</text>
								</view>
							</view>
							<u-line dashed margin="10rpx 0"></u-line>
							<block v-for="(subItem, index) in item.items" :key="index">
								<view class="flex box-border mt-[20rpx]">
									<u--image width="150rpx" height="150rpx" :radius="'var(--goods-rounded-big)'"
										:src="img(subItem.picUrl ? subItem.picUrl : '')" mode="aspectFill">
										<template #error>
											<image class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
												:src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill"></image>
										</template>
									</u--image>
									<view class="ml-[20rpx] flex flex-1 flex-col justify-between box-border">
										<view class="flex justify-between items-baseline">
											<view class="max-w-[322rpx] text-[32rpx] leading-[40rpx] font-bold truncate text-[#303133]">

												<view class="brand-tag">
													{{ (subItem.spuType == 2 || subItem.spuType ==
														4) ? formatSkuType(subItem.skuType) : formatSpuType(subItem.spuType)
													}}
												</view>

												{{
													subItem.spuName }}
											</view>

											<view class="text-right leading-[42rpx] ml-[10rpx] ">
												<uni-tooltip :content="'实售单价'" @click.stop placement="left">
													<uni-icons type="info" size="14"></uni-icons>
													<template #content>
														<view class="w-100rpx">
															实售单价
														</view>
													</template>
												</uni-tooltip>
												<text class="text-[22rpx] price-font">￥</text>
												<text class="text-[36rpx] font-500 price-font">{{
													parseFloat(diyGoods.fen2yuan(subItem.singlePrice)).toFixed(2).split('.')[0]
												}}</text>
												<text class="text-[22rpx] font-500 price-font">.{{
													parseFloat(diyGoods.fen2yuan(subItem.singlePrice)).toFixed(2).split('.')[1]
												}}</text>
											</view>
										</view>
										<view class="flex justify-between items-center text-[#303133] ">
											<view
												class="text-[28rpx] text-[var(--text-color-light6)] font-400 truncate leading-[34rpx] max-w-[369rpx] ">
												<text v-if="subItem?.properties">{{ skuSpecFormat(subItem.properties) }}</text>
												<template v-if="subItem?.spuType == 2">
													<text v-if="subItem?.properties?.length">|</text>
													<text>{{
														filterCardAttributes(subItem, true, true) }}</text>
												</template>
												<text
													v-if="(subItem?.properties || subItem?.spuType == 2) && formatAdminAfterSaleStatus(subItem?.afterSaleStatus)">|</text>

												<text>{{
													formatAdminAfterSaleStatus(subItem?.afterSaleStatus) }}</text>
											</view>
											<text class="line-through text-[var(--text-color-light6)] text-[28rpx]">￥{{
												fen2yuan(subItem.price) }}</text>
										</view>
										<view class="flex justify-end items-center  text-[#303133] ">

											<text class="text-right text-[28rpx] font-400 w-[90rpx] leading-[36rpx]">x{{ subItem.count
											}}</text>
										</view>

									</view>
								</view>
							</block>
						</view>
						<view class="flex justify-end items-center mt-[10rpx]">
							<view class="flex items-baseline flex-wrap justify-end ">
								<view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]">订单实售：</view>
								<view class="leading-[1]  mr-[6rpx]">
									<text class="text-[22rpx] leading-[28rpx] price-font">￥</text>
									<text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{
										parseFloat(diyGoods.fen2yuan(item.realPrice)).toFixed(2).split('.')[0] }}</text>
									<text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{
										parseFloat(diyGoods.fen2yuan(item.realPrice)).toFixed(2).split('.')[1] }}</text>
								</view>

								<view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]" v-if="item.assetPrice > 0">资产抵扣：
								</view>
								<view class="leading-[1]   mr-[6rpx]" v-if="item.assetPrice > 0">
									<text class="text-[22rpx] leading-[28rpx] price-font">￥</text>
									<text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{
										parseFloat(diyGoods.fen2yuan(item.assetPrice)).toFixed(2).split('.')[0] }}</text>
									<text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{
										parseFloat(diyGoods.fen2yuan(item.assetPrice)).toFixed(2).split('.')[1] }}</text>
								</view>
								<view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]" v-if="item.leavePrice > 0">订单欠款：
								</view>
								<view class="leading-[1] text-[var(--price-text-color)]  mr-[6rpx]" v-if="item.leavePrice > 0">
									<text class="text-[22rpx] leading-[28rpx] price-font">￥</text>
									<text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{
										parseFloat(diyGoods.fen2yuan(item.leavePrice)).toFixed(2).split('.')[0] }}</text>
									<text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{
										parseFloat(diyGoods.fen2yuan(item.leavePrice)).toFixed(2).split('.')[1] }}</text>
								</view>
								<view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]">订单实付:</view>
								<view class="leading-[1] text-[var(--price-text-color)]">
									<text class="text-[22rpx] leading-[28rpx] price-font">￥</text>
									<text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{
										parseFloat(diyGoods.fen2yuan(item.otherPrice)).toFixed(2).split('.')[0] }}</text>
									<text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{
										parseFloat(diyGoods.fen2yuan(item.otherPrice)).toFixed(2).split('.')[1] }}</text>
								</view>
							</view>
						</view>
						<!-- 会员信息 -->
						<memberInfo :member="item?.user" v-if="item?.user"></memberInfo>
						<!-- 订单备注 -->
						<remarkInfo :order="item"></remarkInfo>
					</view>
				</template>
			</view>
			<mescroll-empty v-if="!list.length && loading" :option="{ tip: '暂无订单' }"></mescroll-empty>
		</mescroll-body>

		<!-- 订单筛选 -->
		<select-order-search ref="selectOrderSearchRef" :default-date="create_time" :trade-date="trade_time"
			:time-type-list="timeTypeList" :status-tabs="orderStateList" :source-list="orderSourceList"
			:order-type-list="orderTypeList" @confirm="confirmSearchFn"></select-order-search>
		<pay ref="payRef" @close="payClose"></pay>
		<!-- #ifdef MP-WEIXIN -->
		<!-- 小程序隐私协议 -->
		<wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>
		<!-- #endif -->
	</view>
	<!-- 水印 -->
	<watermark></watermark>
</template>

<script setup lang="ts">
import { ref, nextTick, computed } from 'vue';
import { t } from '@/locale'
import { img, redirect, copy, goback } from '@/utils/common'

import { getShopOrder } from '@/addon/shop/api/shopOrder';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import { onLoad, onPageScroll, onReachBottom, onShow, onUnload } from '@dcloudio/uni-app';
import { formatOrderStatus, skuSpecFormat, formatOrderType, timeFormat, formatSpuType, filterCardAttributes, formatSkuType, formatAdminAfterSaleStatus, fen2yuan, getNowMonthDate } from "@/utils/formatting"
import { useGoods } from '@/addon/shop/hooks/useGoods'
import memberInfo from '@/addon/components/order/memberInfo.vue'
import remarkInfo from '@/addon/components/order/remarkInfo.vue';
const diyGoods = useGoods();


const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const list = ref<any>([]);
const loading = ref<boolean>(false);
const statusLoading = ref<boolean>(true);
const orderState = ref('')
const orderShowType = ref('employee') //订单展示类型 employee 门店员工  member 会员
const orderStateList: any = ref([

	{
		name: '全部',
		status: undefined
	},
	{
		name: "待支付",
		status: 0
	},

	{
		name: "已支付",
		status: 2
	},
	{
		name: "待发货",
		status: 10
	},
	{
		name: "已发货",
		status: 20
	},
	{
		name: "已完成",
		status: 30
	},
	{
		name: "已取消",
		status: 40
	},
	{
		name: "已撤销",
		status: 50
	},
	{
		name: '待评价',
		status: 60
	},
	{
		name: '有欠款',
		status: 70
	},
	{
		name: '待核销',
		status: 80
	},
	{
		name: '到店付',
		status: 90
	},
	{
		name: '已核销',
		status: 100
	}
]);
const orderType = ref(undefined)
const orderSource = ref(undefined)
const orderSourceList: any = ref([
	{
		name: '全部',
		status: undefined
	},
	{
		name: '门店',
		status: 4
	},
	{
		name: '商城',
		status: 5
	}
])
const orderTypeList: any = ref([
	{
		name: '全部',
		status: undefined
	},
	{
		name: '普通订单',
		status: 0
	},
	{
		name: '秒杀订单',
		status: 1
	},
	{
		name: '砍价订单',
		status: 2
	},
	{
		name: '拼团订单',
		status: 3
	},
	{
		name: '积分商城',
		status: 4
	},
	{
		name: '活动订单',
		status: 6
	}
])

/** 搜索类型 */
const searchType = ref([{ name: '门店订单', value: 0 }, { name: '个人订单', value: 1 }])
const searchTypeIndex = ref(0)
const updateSearchType = (index: number) => {
	searchTypeIndex.value = index;
	getMescroll().resetUpScroll();
}
const wxPrivacyPopupRef: any = ref(null)
const toCall = (phoneNumber: any) => {
	console.log(phoneNumber)

	uni.makePhoneCall({
		phoneNumber: phoneNumber //仅为示例
	});
}
const query = ref<any>(undefined);//查询类型
onLoad((option: any) => {
	query.value = 0
	orderState.value = option.status || "";
	orderShowType.value = option.type || "employee";
	if (orderShowType.value == 'employee') {
		create_time.value = getNowMonthDate()
		query.value = undefined
		console.log(query.value)

	}

	// getShopOrderStatusFn();
	// #ifdef MP
	nextTick(() => {
		if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
	})
	// #endif
});

/**
 * 订单查询类型
 */
//日期筛选
const time_type = ref('0')  //0创建时间  1 '交易时间'
const timeTypeList = [{
	name: '创建时间',
	status: '0'
},
{
	name: '交易时间',
	status: '1'
}]

const create_time = ref<any>([])
const create_time_str = computed(() => {
	let beginTime = create_time.value[0] ? create_time.value[0].split(' ')[0] : '';
	let endTime = create_time.value[1] ? create_time.value[1].split(' ')[0] : '';
	if (beginTime && endTime) {
		return beginTime + ' - ' + endTime

	} else {
		return ''
	}

})
const trade_time = ref<any>([])


//订单筛选
const keyword = ref('')

const selectOrderSearchRef = ref()
const handleSelectOrderSearch = () => {
	selectOrderSearchRef.value.show = true
}
const confirmSearchFn = (data: any) => {
	orderState.value = data.status;
	orderType.value = data.type;
	orderSource.value = data.source;
	create_time.value = data.create_time;
	trade_time.value = data.trade_time;
	keyword.value = data.keyword;
	list.value = []
	getMescroll().resetUpScroll();
}
/**
 * 支付弹窗关闭
 */
const payClose = () => {
	nextTick(() => {
		// 评价完成之后，会返回到订单列表，需要请求最新数据
		if (getMescroll()) { getMescroll().resetUpScroll(); }
	})
}
onShow(() => {
	const options = uni.getEnterOptionsSync();
	// scene 1038	从另一个小程序返回
	// #ifdef MP
	if (options.scene == 1038) {
		uni.$emit('scene', {
			scene: 1038
		})
		return
	}
	// #endif
	nextTick(() => {

		if (getMescroll()) {

			getMescroll().resetUpScroll();
		}
	})
})
onUnload(() => {
	uni.$off('scene')
})

let wap_member_id = uni.getStorageSync('wap_member_id');
let wap_shop_member_id = uni.getStorageSync('wapShopMember').id;

const getShopOrderFn = (mescroll: any) => {

	loading.value = false;
	let api = getShopOrder

	let data: object = {
		pageNo: mescroll.num,
		pageSize: mescroll.size,
		status: orderState.value,
		employeeName: searchTypeIndex.value == 0 ? undefined : wap_member_id, //员工名称
		typeClass: 0, //订单分类 0 销售订单（默认）
		userId: orderShowType.value == "employee" ? undefined : wap_shop_member_id, //用户id
		createTime: create_time.value, //创建时间
		tradeTime: trade_time.value, //交易时间
		type: orderType.value, //订单类型
		source: orderSource.value,//订单来源
		keywords: keyword.value, //关键词
		query: query.value
	};
	api(data).then((res: any) => {
		let newArr = (res.data.list as Array<Object>);
		//设置列表数据
		if (mescroll.num == 1) {
			list.value = []; //如果是第一页需手动制空列表
		}



		list.value = list.value.concat(newArr);

		mescroll.endSuccess(newArr.length);

		loading.value = true;
	}).catch(() => {
		loading.value = true;
		mescroll.endErr(); // 请求失败, 结束加载
	})
}




const toLink = (data: any) => {

	redirect({ url: '/addon/shop/pages/shopOrder/detail', param: { order_id: data.id } })


}





</script>
<style lang="scss">
@import '@/addon/shop/styles/common.scss';

.order-list .mescroll-body {
	padding-bottom: constant(safe-area-inset-bottom) !important;
	padding-bottom: env(safe-area-inset-bottom) !important;
}

.order-list :deep(.u-count-down__text) {
	font-size: 24rpx !important;
	color: #EF000C !important;
}
</style>
<style lang="scss" scoped>
.text-color {
	color: var(--primary-color);
}

.bg-color {
	background-color: var(--primary-color);
}
</style>
